import request from "../../utils/request";
import getCartID from '../../utils/getCart_id'
// components/footer/footer.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    num: {
      type: Number
    },
    price: {
      type: Number
    },
    sku: {
      type: Array
    },
    good_id: {
      type: Number
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    async addcart() {
      let userInfo=wx.getStorageSync('userInfo')
     if(userInfo){
      let sku = this.properties.sku.join()
      let token = wx.getStorageSync('userInfo').token
      let Obj = {
        token,
        sku,
        good_id: this.properties.good_id,
        num: this.properties.num,
        price: this.properties.price,
        money: this.properties.num * this.properties.price
      }
     let shoppingInfo=await getCartID({good_id:this.properties.good_id,sku});
    if(shoppingInfo.shopping_car_id){
      Obj.shopping_car_id=shoppingInfo.shopping_car_id
      Obj.num=this.properties.num+shoppingInfo.num
      Obj.money=(this.properties.num * this.properties.price)+(shoppingInfo.money*1)
    }else{
      delete Obj.shopping_car_id
    }
      let res = await request("/api/shoppingCarAddModify", Obj)
      if (res.code === 2000) {
        this.storage(Obj)
        wx.showToast({
          title: '添加成功',
        })
      }
     }else{
       wx.navigateTo({
         url: '../../pages/login/login',
       })
     }
    },
    storage(Obj) {
      let selectCart = wx.getStorageSync("selectCart")
      if (selectCart) {
        let flag = false
        selectCart.forEach(item => {
          if (!flag) {
            if (item.good_id == Obj.good_id && JSON.stringify(item.sku)==JSON.stringify(Obj.sku)) {
              item.state = true
              flag = true
            }
          }
        })
        if (!flag) {
          selectCart.push({
            good_id: Obj.good_id,
            state: true,
            sku:Obj.sku
          })
        }
        wx.setStorageSync('selectCart', selectCart)
      } else {
        wx.setStorageSync('selectCart', [{
          good_id: Obj.good_id,
          state: true,
          sku:Obj.sku
        }])
      }
    },
    toCart(){
      wx.switchTab({
        url: '../../pages/cart/cart',
      })
    }
  },
  // 存在本地

  ready() {
    
  }
})